package com.sinry.common.log.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.contrib.json.classic.JsonLayout;
import cn.hutool.core.date.DateUtil;
import com.sinry.common.log.utils.IpUtils;
import com.sinry.common.log.utils.TraceIdUtil;

import java.util.Map;

/**
 * @author linxinlei
 * @project sinry-cloud
 * @description 增强版layout扩展
 * @date 2022/6/5
 **/
public class JsonLayoutPlus extends JsonLayout {

    public static final String TRACE_ID = TraceIdUtil.TRACE_ID;
    public static final String PARENT_ID = TraceIdUtil.PARENT_ID;
    public static final String SPAN_ID = TraceIdUtil.SPAN_ID;
    public static final String REQUEST_IP = IpUtils.REQUEST_IP;
    public static final String APP_NAME = "app";
    public static final String DATE = "date";

    protected boolean includeTraceId;
    protected boolean includeParentId;
    protected boolean includeSpanId;
    protected boolean includeIp;
    protected boolean includeAppName;
    protected String appName;

    public JsonLayoutPlus() {
        super();
        // 关闭MDC显示，直接扁平化json
        this.includeMDC = false;
        this.includeTraceId = true;
        this.includeParentId = true;
        this.includeSpanId = true;
        this.includeIp = true;
        this.includeAppName = true;
        // 关闭上下文显示
        this.includeContextName = false;

    }

    @Override
    protected Map toJsonMap(ILoggingEvent event) {
        Map map = super.toJsonMap(event);
        add(TRACE_ID, this.includeTraceId, TraceIdUtil.getTraceId(), map);
        add(PARENT_ID, this.includeParentId, TraceIdUtil.getParentId(), map);
        add(SPAN_ID, this.includeSpanId, TraceIdUtil.getSpanId(), map);
        add(REQUEST_IP, this.includeIp, IpUtils.getLogIp(), map);
        add(APP_NAME, this.includeAppName, getAppName(), map);
        add(DATE, super.includeTimestamp, DateUtil.date(event.getTimeStamp()).toString("yyyy-MM-dd HH:mm:ss"), map);
        return map;

    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }
}
